package org.example.test.controller;

import org.example.test.dal.entity.Coupons;
import org.example.test.model.CouponsModel;
import org.example.test.response.CommonResponse;
import org.example.test.response.ResponseBuilder;
import org.example.test.service.CouponsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 优惠券控制器
 * 提供优惠券相关的增删查接口
 */
@RestController
@RequestMapping("/coupons")
public class CouponsController {
    // 日志记录器
    private static final Logger LOGGER = LoggerFactory.getLogger(CouponsController.class);

    @Autowired
    private CouponsService couponsService;  // 优惠券服务

    /**
     * 查询优惠券接口
     * @param merchantId 商户ID
     * @return 返回优惠券信息
     */
    @PostMapping("/selectCoupons")
    public CommonResponse selectCoupons(@RequestParam Long merchantId) {
        try {
            LOGGER.info("selectCoupons request: {}", merchantId);
            Coupons coupons = couponsService.selectCoupons(merchantId);  // 调用服务层查询优惠券
            return ResponseBuilder.success(coupons);  // 返回成功响应
        } catch (Exception e) {
            LOGGER.error("查询优惠券出错", e);  // 记录错误日志
            return ResponseBuilder.error(e.getMessage());  // 返回错误响应
        }
    }

    /**
     * 添加优惠券接口
     * @param couponsModel 优惠券模型
     * @return 返回操作结果
     */
    @PostMapping("/addCoupons")
    public CommonResponse addCoupons(@RequestBody CouponsModel couponsModel) {
        try {
            LOGGER.info("addCoupons request: {}", couponsModel);
            couponsService.addCoupons(couponsModel);  // 调用服务层添加优惠券
            return ResponseBuilder.success("0");  // 返回成功响应
        } catch (Exception e) {
            LOGGER.error("添加优惠券出错", e);  // 记录错误日志
            return ResponseBuilder.error(e.getMessage());  // 返回错误响应
        }
    }

    /**
     * 删除优惠券接口
     * @param merchantId 商户ID
     * @return 返回操作结果
     */
    @PostMapping("/deleteCoupons")
    public CommonResponse deleteCoupons(@RequestParam Long merchantId) {
        try {
            LOGGER.info("deleteCoupons request: {}", merchantId);
            couponsService.deleteCoupons(merchantId);  // 调用服务层删除优惠券
            return ResponseBuilder.success("0");  // 返回成功响应
        } catch (Exception e) {
            LOGGER.error("删除优惠券出错", e);  // 记录错误日志
            return ResponseBuilder.error(e.getMessage());  // 返回错误响应
        }
    }
}